package com.sunchangming.benchmark;

import java.nio.*;

public class BufferMark2 {
	private final float[] array = new float[10000];
	private final FloatBuffer byteBuffer = ByteBuffer.allocateDirect(40000).order(ByteOrder.nativeOrder())
			.asFloatBuffer();

	protected void testWrite() {
		// Allow VM to compile
		testWriteArray(1000);
		testWriteByteBuffer(1000);
		// Test for real
		System.out.println("Array buffer: " + testWriteArray(50000) + " us per iteration");
		System.out.println("Direct buffer: " + testWriteByteBuffer(50000) + " us per iteration");
	}

	protected double testWriteByteBuffer(int iterations) {
		long timeNow = System.currentTimeMillis();
		for (int j = 0; j < iterations; j++) {
			for (int i = 0; i < 10000; i++) {
				byteBuffer.put(i, 1234.5678f);
			}
		}
		return 1000.0 * (System.currentTimeMillis() - timeNow) / iterations;
	}

	protected double testWriteArray(int iterations) {
		long timeNow = System.currentTimeMillis();
		for (int j = 0; j < iterations; j++) {
			for (int i = 0; i < 10000; i++) {
				array[i] = 1234.5678f;
			}
		}
		return 1000.0 * (System.currentTimeMillis() - timeNow) / iterations;
	}

	public BufferMark2() {
	}

	public static void main(String[] args) {
		for (int n = 0; n < 10; n++) {
			System.out.println("=== round " + n);
			BufferMark2 app = new BufferMark2();
			app.testWrite();
		}
	}

}
